<template>
    <div>
        <el-dialog v-model="dialogVisible" width="75%" align-center :close-on-click-modal="false" :show-close="false"
            :before-close="handleClose" destroy-on-close draggable>
            <template #header="{ close }">
                <div class="dialog-header flex justify-between items-center">
                    <div>{{ title }}导出</div>
                    <el-icon class="el-icon--left cursor-pointer" @click="close">
                        <CircleCloseFilled color="#fff" />
                    </el-icon>
                </div>
            </template>
            <div>
                <div class="bg-white mt-[10px]">
                    <BaseHead>可选属性 ({{ extendsList.length }}项)
                        <template v-slot:Rslot>
                            <el-button @click="addAll">全部添加</el-button>
                        </template>
                    </BaseHead>
                    <div class="p-[10px]">
                        <span class="pt-[10px] pl-[15px] pr-[15px] extendBox" v-for="item in extendsList"
                            :key="item.value">
                            <span @click="changSelect(item)" :class="item.isSelect ? 'selectType' : ''"
                                class="pl-[20px] pr-[0px] extendItem">{{
            item.lable
        }}<el-icon style="margin-left: 10px;" v-if="item.isSelect"><Select /></el-icon></span>
                        </span>
                    </div>
                </div>
                <div class="bg-white mt-[10px]">
                    <BaseHead> <span>导出预览 ({{ tableData.columnList.length }}项)<span
                                style="font-size: 10px;color: #666;margin-left: 6px;font-style: italic;">用鼠标拽动可以调整属性顺序</span></span>
                        <template v-slot:Rslot>
                            <el-button @click="cancelAll">全部取消</el-button>
                        </template>
                    </BaseHead>
                    <div class="p-[20px]">
                        <el-table ref="tableRef" :data="tableData.data" :key="'table' + tableData.key"
                            @header-dragend="handleHeaderDragend" border style="width: 100%">
                            <template v-for="(item, index) of tableData.columnList" :key="index">
                                <el-table-column show-overflow-tooltip :resizable="false" :prop="item.prop"
                                    :label="getRowLabel(index)" align="center" header-align="center"
                                    min-width="140"></el-table-column>
                            </template>
                        </el-table>
                    </div>
                </div>


            </div>
            <template #footer>
                <div class="dialog-footer">
                    <div class="operate-btns">
                        <el-button type="primary" @click="exportMet">导出</el-button>
                        <el-button type="primary" @click="close">关闭</el-button>
                    </div>
                </div>
            </template>
        </el-dialog>
    </div>
</template>
<script setup>
import Sortable from 'sortablejs';
import { nextTick } from 'vue';
import BaseHead from "@/views/project/components/BaseHead.vue";
import { ElMessage } from "element-plus";
import _ from "lodash";
const props = defineProps({
    selectList: {
        type: Array,
        default() {
            return []
        }
    },
    title: {
        type: String,
        default() {
            return ''
        }
    },
    drag: {
        type: Boolean,
        default() {
            return true
        }
    }
})

const tableData = reactive({
    key: new Date().getTime(),
    data: [{

    }],
    columnList: [
        // {
        //     label: 'ID',
        //     prop: "id",
        //     width: "180"
        // },
    ]
})
const dialogVisible = defineModel();
const emit = defineEmits(['callBack']);
const handleClose = (done) => {
    initData()
    done();
}
const close = () => {
    dialogVisible.value = false;
    initData()
}
const exportMet = () => {
    if (tableData.columnList.length) {
        dialogVisible.value = false;
        emit('callBack', tableData.columnList)
        initData()
    } else {
        ElMessage({
            message: '请选择需要导出的导出项!',
            type: 'warning',
        })
    }
}

const initData = () => {
    tableData.columnList = []
    tableData.data[0] = {}
}




const tableRef = ref();
let sortable = null // 接收Sortable实例化对象，不能用响应式变量接收Sortable实例化对象
function initTableHeaderDrag() {
    if (sortable) {
        sortable.destroy();
    }
    let el = tableRef.value.$el.querySelector('.el-table__header-wrapper tr')
    sortable = Sortable.create(el, {
        animation: 150,
        onEnd(evt) {
            const oldItem = tableData.columnList[evt.oldIndex];
            tableData.columnList.splice(evt.oldIndex, 1);
            tableData.columnList.splice(evt.newIndex, 0, oldItem);
            tableData.key = new Date().getTime(); // 变更key，强制重绘table。如果不强制变更的话，会出现一些奇奇怪怪的问题，列宽度调整也会出现问题
            nextTick(() => {
                initTableHeaderDrag(); // 因为table被强制重新绘制，因此需要重新监听
            })
            console.log(tableData.data)
            console.log(tableData.columnList)
        }
    })
}
function handleHeaderDragend(newWidth, oldWidth, column, event) {
    for (let item of tableData.columnList) {
        if (item.label == column.label) {
            item.width = newWidth;
        }
    }
    initTableHeaderDrag(); // 重新注册，防止变更宽度后无法拖动
}


const getRowLabel = (index) => {
    let base = "A".charCodeAt(0);
    let quotient = Math.floor(index / 26); // 商
    let remainder = index % 26; // 余数
    if (quotient > 0) {
        return String.fromCharCode(base + quotient - 1) + String.fromCharCode(base + remainder);
    } else {
        return String.fromCharCode(base + remainder);
    }
}
const changSelect = (i) => {
    if (i.isSelect) {
        tableData.columnList = tableData.columnList.filter(item => item.prop != i.value)
        delete tableData.data[0][i.value]
    } else {
        tableData.columnList.push({
            label: tableData.columnList.length,
            prop: i.value,
        },)
        tableData.data[0][i.value] = i.lable
    }
    i.isSelect = !i.isSelect
}

const extendsList = ref([])
const cancelAll = () => {
    extendsList.value.forEach(i => {
        i.isSelect = false
    })
    tableData.columnList = []
    tableData.data[0] = {}
}
const addAll = () => {
    extendsList.value.forEach(i => {
        if (!i.isSelect) {
            tableData.columnList.push({
                label: tableData.columnList.length,
                prop: i.value,
            },)
            tableData.data[0][i.value] = i.lable
            i.isSelect = true
        }
    })
}
watch(
    () => dialogVisible.value,
    (newValue) => {
        if (newValue) {
            extendsList.value = _.cloneDeep(props.selectList)
            extendsList.value.forEach(i => {
                if (i.isSelect) {
                    tableData.columnList.push({
                        label: tableData.columnList.length,
                        prop: i.value,
                    },)
                    tableData.data[0][i.value] = i.lable
                }
            });
            nextTick(() => {
                initTableHeaderDrag(); // 初始化拖拽事件
            })

        }
    },
    { deep: true, immediate: true }
);
</script>
<style scoped lang="scss">
@import url("@/views/achievement/index.scss");

.extendBox {
    height: 40px;
    display: inline-block;

    .extendItem {
        width: 180px;
        height: 30px;
        line-height: 30px;
        display: inline-block;
        cursor: pointer;
        font-size: 12px;
        color: #666
    }

    .extendItem:hover {
        background-color: rgba(36, 148, 242, 0.1);
    }

    .selectType {
        color: #2394F2;
    }
}
</style>
